package com.zzt.video.controller;

import com.zzt.video.model.dto.AdvertiseDto;
import com.zzt.video.model.dto.AdvertiseShowDto;
import com.zzt.video.model.entity.Advertise;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/advertise")
public class AdvertiseController {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 获取广告列表
     */
    @GetMapping("/list")
    public ResponseEntity<List<AdvertiseShowDto>> getAdvertiseList() {
        RBucket<List<AdvertiseShowDto>> advertiseBucket = redissonClient.getBucket("advertise:list");
        List<AdvertiseShowDto> list = advertiseBucket.get();
        if (list == null) {
            // 缓存未命中，从数据库获取
            list = new ArrayList<>();
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 根据ID获取广告详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<AdvertiseDto> getAdvertiseById(@PathVariable Long id) {
        RBucket<AdvertiseDto> advertiseBucket = redissonClient.getBucket("advertise:detail:" + id);
        AdvertiseDto dto = advertiseBucket.get();
        // 如果查不到数据，返回新建对象
        return ResponseEntity.ok(dto != null ? dto : new AdvertiseDto(new Advertise()));
    }
}
